import { guid } from "@/utils";
import { emitter } from "@/utils/mitt";
import {
  clearAllStats,
  colorList,
} from "@/views/buildKg/ontology/common/index";
import { graph } from "./index";
import { nodeOptions } from "@/views/buildKg/ontology/common/state";
import { delVerifyApi } from "@/api/buildKg/tology";
import { ElMessage } from "element-plus";

export const handleCopyObject = (ev) => {
  // setAllStateDark();
  const model = ev.item.getModel();
  const id = guid();
  graph.addItem(
    "node",
    {
      ...model,
      id: id,
      label: `object_${id}`,
      labelName: `object_${id}`,
      x: model.x + 10,
      y: model.y + 10,
    },
    true
  );
};

export const handleDeleteObject = async (currentEvt) => {
  const currentModel = currentEvt.item;
  const currentNode = currentModel.getModel();
  const type = currentModel.getType();

  if (!currentNode.code) {
    graph.removeItem(currentModel);
  } else {
    const params = {
      codeList: currentNode.code,
      type: type === "node" ? 1 : 2,
    };
    const { code, data } = await delVerifyApi(params);
    if (code === 200 && !data.length) {
      graph.removeItem(currentModel);
    } else {
      ElMessage.error(
        "该对象下有知识无法进行删除,请在知识管理中批量删除该对象下的知识后再进行操作"
      );
    }
  }
};

export const handleBuildRelation = (currentEvt) => {
  console.log(currentEvt);
};

export const handleEditObject = (currentEvt) => {
  currentEvt.item && currentEvt.item.getType().toUpperCase() === "EDGE"
    ? emitter.emit("handleTologyLineEdit", currentEvt)
    : emitter.emit("handleTologyEdit", currentEvt);
};

export const handleAllConcept = () => {
  clearAllStats();
  graph.getNodes().forEach((node) => {
    graph.setItemState(node, "highlight", true);
  });
  graph.getEdges().forEach((edge) => {
    graph.setItemState(edge, "lineDark", true);
  });
};

export const handleAllRelation = () => {
  clearAllStats();
  graph.getNodes().forEach((node) => {
    graph.setItemState(node, "dark", true);
  });
  graph.getEdges().forEach((edge) => {
    graph.setItemState(edge, "selected", true);
  });
};

export const handleAllChoose = () => {
  clearAllStats();
  graph.getNodes().forEach((node) => {
    graph.setItemState(node, "highlight", true);
  });
  graph.getEdges().forEach((edge) => {
    graph.setItemState(edge, "selected", true);
  });
};

export const handleBuildObject = (ev) => {
  // Add a new node
  const rand = Math.floor(Math.random() * 10);
  const id = guid();
  graph.addItem("node", {
    x: ev.x,
    y: ev.y,
    id: id, // Generate the unique id
    label: `object_${id}`,
    labelName: `object_${id}`,
    isAdd: true,
    style: {
      fill: colorList[rand],
    },
    labelCfg: {
      style: {
        fill: colorList[rand],
      },
    },
    stateStyles: nodeOptions({ backgroundColor: colorList[rand] }),
  });
};
